package com.example.demotest.controller;

import com.example.demotest.pojo.Order;
import com.example.demotest.pojo.Order.DeliveryStatus;
import com.example.demotest.pojo.OrderStatus;
import com.example.demotest.pojo.ResponseMessage;
import com.example.demotest.pojo.Rider;
import com.example.demotest.pojo.dto.RiderDto;
import com.example.demotest.service.IAdminService;
import com.example.demotest.service.IRiderService;
import com.example.demotest.service.OrderService;
import com.example.demotest.service.RiderService;
import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/rider")
public class RiderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    IRiderService riderService; // 注入 service

    @Autowired
    private JWT jwt;

    /**
     * 骑手注册
     */
    @PostMapping("/register")
    public ResponseMessage<Rider> register(@RequestBody @Valid RiderDto riderDto) {
        try {
            Rider newRider = riderService.register(riderDto);
            return ResponseMessage.success(newRider);
        } catch (Exception e) {
            return ResponseMessage.error(400, e.getMessage());
        }
    }

    /**
     * 骑手登录
     */
    @PostMapping("/login")
    public ResponseMessage<Rider> login(@RequestBody @Valid RiderDto riderDto) {
        return riderService.login(riderDto);
    }

    // 获取所有待接单的订单（商家已发货，但未接单）
    @GetMapping("/orders")
    public ResponseMessage<List<Order>> getAvailableOrders() {
        List<Order> orders = orderService.getAvailableOrders();
        return ResponseMessage.success(orders);
    }

    // 获取骑手自己接的所有订单
    @GetMapping("/my-orders")
    public ResponseMessage<List<Order>> getMyOrders(HttpServletRequest request) {
        Integer riderId = jwt.getUserIdFromToken(jwt.extractToken(request));
        List<Order> orders = orderService.findOrdersByRiderId(riderId);
        return ResponseMessage.success(orders);
    }

    @PutMapping("/accept/{orderId}")
    public ResponseMessage<String> acceptOrder(HttpServletRequest request, @PathVariable Integer orderId) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401,"请先登录");
        }

        Integer riderId = jwt.getUserIdFromToken(token);
        // 查找订单
        Order order = orderService.getOrderById(orderId);
        if (order == null || !order.getOrderStatus().equals(OrderStatus.WAIT_SHIP.getCode())) {
            return ResponseMessage.error(400, "接单失败：订单不存在或状态错误");
        }

        // 设置相关字段
        order.setRiderId(riderId);
        order.setDeliveryStatus(DeliveryStatus.IN_TRANSIT);
        order.setPickupTime(LocalDateTime.now());
        order.setOrderStatus(OrderStatus.WAIT_RECEIVE.getCode());

        orderService.save(order);

        return ResponseMessage.success("接单成功");
    }

    // 完成订单（骑手完成配送）
    @PutMapping("/complete/{orderId}")
    public ResponseMessage<String> completeOrder(@PathVariable Integer orderId,
                                                 HttpServletRequest request) {
        Integer riderId = jwt.getUserIdFromToken(jwt.extractToken(request));
        Order order = orderService.getOrderById(orderId);

        if (order == null) {
            return ResponseMessage.error(404, "订单不存在");
        }

        // 校验是否是当前骑手，且状态为“配送中”
        if (!riderId.equals(order.getRiderId()) ||
                order.getDeliveryStatus() != DeliveryStatus.IN_TRANSIT) {
            return ResponseMessage.error(403, "无权完成该订单或状态错误");
        }

        // 更新订单状态
        order.setDeliveryStatus(DeliveryStatus.DELIVERED);
        order.setOrderStatus(OrderStatus.COMPLETED.getCode());
        order.setDeliveryTime(LocalDateTime.now());

        orderService.save(order);

        return ResponseMessage.success("订单已完成");
    }
}
